package com.android.view.hqview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.android.presenter.contract.HqFenXianContract;
import com.android.util.DateUtils;
import com.android.presenter.HqFenXianPresenter;
import com.android.util.DateUtil;
import com.android.util.MinutesType;
import com.android.util.MinutesTypeFactory;
import com.mp.chart.charts.MinutesChart;
import com.mp.chart.data.Entry;
import com.mp.chart.data.MinutesData;
import com.mp.chart.formatter.DataFormatter;
import com.mp.chart.formatter.YValueFormatter;
import com.mp.chart.listener.OnMarketSelectValueListener;
import com.mp.chart.markerview.HightCircleMarkerView;
import com.mp.chart.markerview.LeftMarkerView;
import com.mp.chart.markerview.QuoteInfoMarkerView;
import com.mp.chart.markerview.RightMarkerView;
import com.mp.chart.markerview.XAxisMarkerView;
import com.mp.chart.utils.PriceColorUtil;
import com.mp.chart.utils.StringUtils;
import com.mp.chart.utils.VolumeUtils;
import com.mp.chart.view.ShinePointView;
import com.android.R;
import com.android.model.entity.res.QuoteStockMinutesData;
import com.android.model.info.LocalSp;
import com.android.model.net.AppBaseNetWork;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by TenFace on 17/10/25.
 * 分时View
 */

@SuppressLint("ViewConstructor")
public class MinutesView extends BaseChartView implements HqFenXianContract.View, OnMarketSelectValueListener {
    private static final String TAG = "MinutesView";
    private HqFenXianPresenter presenter;
    private MinutesChart mMinutesChart;
    private int count;
    private float lastClose = 0;
    private float maxmin;
//    private FrameLayout chartTopHigh;
    private float volmax;
    private View v;
    private boolean isFullScreen;
    private TextView highTime, highOpen, highHigh, highLow, highClose, highFu;
    private String upColor, downColor, equalColor, tvColor;
    private ArrayList<MinutesData> minutesDatas;
    private List<QuoteStockMinutesData.DataBean> minuteList;
    private boolean isZS = false;

    public MinutesView(Context context, FrameLayout v, Bundle bundle) {
        super(context, bundle);
//        this.chartTopHigh = v;
//        Log.e(TAG, "MinutesView 构造方法调用次数");
    }

    public MinutesView(Context context, Bundle bundle) {
        super(context, bundle);
    }

    @Override
    public int getLayoutId() {
        return R.layout.chart_minutes;
    }

    @Override
    public void initLayout(Context context) {
        mMinutesChart = (MinutesChart) findViewById(R.id.minutesChart);
        initChart();
//        initTabHighLightView();

    }



    @Override
    public void initData() {
        String type = mBundle.getString("type");
        String name = mBundle.getString("name");
        isFullScreen = mBundle.getBoolean("fullScreen");
        presenter = new HqFenXianPresenter(this, "", "1", mMinutesChart);
//        Log.e("initData()","调用次数");
        presenter.getLine();
    }

//    private void initTabHighLightView() {
//        v = LayoutInflater.from(getContext()).inflate(R.layout.hq_highlight_layout, null);
//        highTime = (TextView) v.findViewById(R.id.highTime);
//        highOpen = (TextView) v.findViewById(R.id.highOpen);
//        highHigh = (TextView) v.findViewById(R.id.highHigh);
//        highClose = (TextView) v.findViewById(R.id.highClose);
//        highLow = (TextView) v.findViewById(R.id.highLow);
//        highFu = (TextView) v.findViewById(R.id.highFu);
//    }

    private void initChart() {
        upColor = DataFormatter.colorToString(LocalSp.getInstance(getContext()).getBeginColor());
        downColor = DataFormatter.colorToString(LocalSp.getInstance(getContext()).getEndColor());
        equalColor = DataFormatter.colorToString(getResources().getColor(R.color.mainFontColor));
        tvColor = DataFormatter.colorToString(getResources().getColor(R.color.mainFontColor));
        mMinutesChart.setXAxisLabelColor(getResources().getColor(R.color.mainFontColor));
        mMinutesChart.setGridLineColor(Color.TRANSPARENT);
        mMinutesChart.setHighLightColor(getResources().getColor(R.color.highlight));
        mMinutesChart.setAxisLeftValueFormatter(new YValueFormatter("#0.00"));
        mMinutesChart.setAxisRightValueFormatter(new YValueFormatter("#0.00%"));
        mMinutesChart.setDrawBorder(Color.TRANSPARENT, 1);
        mMinutesChart.setLabelCount(2);
        mMinutesChart.setYAxisOffset(2);
        mMinutesChart.setYLabelStatic(false);//设置y轴label是否固定
        mMinutesChart.setQuoteInfoMarkerView(new QuoteInfoMarkerView("timeline", getContext(), R.layout.quote_info_markerview, false));
        mMinutesChart.setLRMarkerView(
                new QuoteInfoMarkerView("timeline", getContext(), R.layout.quote_info_markerview, false),
                new LeftMarkerView("timeline", getContext(), R.layout.share_marker_view, false, "#0.00"),
                new RightMarkerView("timeline", getContext(), R.layout.share_marker_view, false, "#0.00"),
                new XAxisMarkerView(getContext(), R.layout.share_marker_view, "minutes"));//new XAxisMarkerView(getContext(), R.layout.share_marker_view)
        mMinutesChart.setHighLightCircle(new HightCircleMarkerView(getContext(), getResources().getColor(R.color.highlight)));//十字星圆点颜色
        mMinutesChart.setShinePointView(new ShinePointView(getContext(), getResources().getColor(R.color.main_title_bg)));//分时跳动点的颜色
        mMinutesChart.setSpaceTopAndBottom(10f);
        mMinutesChart.setDrawLinePathFillEnabled(true);
        mMinutesChart.setOnChartGestureListener(this);
        mMinutesChart.setOnMarketSelectValueListener(this);
        mMinutesChart.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return false;
            }
        });

    }

    /*x轴坐标*/
    protected SparseArray<String> initAxisX(int count, long openTime) {
        SparseArray<String> titleX = new SparseArray<String>();
        long average = (count - 1) / 4;
        for (int i = 0; i < 5; i++) {
            int index = (int) Math.floor(i * average);
            if (index > count - 1) {
                index = count - 1;
            }
            String timeX = DateUtil.converTime(Long.parseLong((openTime + i * average * 60000) + ""), "HH:mm", 0);
            titleX.put(index, timeX);
        }

        return titleX;
    }

    @Override
    public void unRegister() {
        super.unRegister();
        if (presenter != null) {
            presenter.onDestroy();
        }
        if (mMinutesChart != null) {
            mMinutesChart.clear();
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        if (presenter != null) {
            presenter.onDestroy();
        }
        if (mMinutesChart != null) {
            mMinutesChart.clear();
        }
    }


    @Override
    public void refreshData() {
//        presenter.getLine();
//        presenter.getNewLine();
//        Log.e("HqFenXianPresenter", "==refreshData刷新啦！");
    }

    @Override
    public void updateHqInfo(List<QuoteStockMinutesData.DataBean> infos) {
        stop();
        if (infos == null) {
            return;
        }
        isZS = true;

        AppBaseNetWork.getInstance().isStockOpeningTime(new AppBaseNetWork.StateCallback() {
            @Override
            public void isSuccess(boolean isSuccess) {
                //开盘时显示跳动点，收盘时隐藏
                if (isSuccess) {
                    mMinutesChart.setShinePointStatus(true);
                } else {
                    mMinutesChart.setShinePointStatus(false);
                }
            }
        });

        if (infos.size() == 0) {
            mMinutesChart.clear();
            mMinutesChart.invalidate();
        } else {
            minutesDatas = new ArrayList<>();
            MinutesType minutesType = MinutesTypeFactory.getType("SH");
            mMinutesChart.setShowLabels(minutesType.getShowTimeLabels()); //显示标签
            float max = (float) infos.get(0).getClose().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
            float min = (float) infos.get(0).getClose().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();

            lastClose = (float) infos.get(0).getLow().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();//昨收
            minuteList = infos;
            float maxPercent = (float) (minuteList.get(0).getClose().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue()/10);
            float minPercent = (float) (minuteList.get(0).getClose().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue()/10);
            count = minuteList.size();
            for (int i = 0; i < count; i++) {
                MinutesData minutesData = new MinutesData();
                float currentPrice = (float) minuteList.get(i).getClose().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();

                float percent = (float) (minuteList.get(i).getClose().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue()/10);
//                float averagePrice = (float) minuteList.get(i).getAvg();
                minutesData.chengjiaojia = currentPrice;
                minutesData.chengjiaoliang = (float) minuteList.get(i).getVolume().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                minutesData.percentage = (float) (minuteList.get(i).getClose().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue()/10);
                minutesData.junjia = (float) minuteList.get(i).getLow().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                minutesData.lastClose = (float) minuteList.get(i).getLow().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
//              minutesData.time = Long.parseLong(minuteList.get(i).getTime());
                minutesData.time = DateUtils.getDateToStringHm(minuteList.get(i).getOpenDateTime());
//                minutesData.time = DateUtils.getNYHmStr(minuteList.get(i).getTime());

                //当前价与最大最小值相比，取最大最小值
                if (currentPrice > max) {
                    max = currentPrice;
                }
                if (currentPrice < min) {
                    min = currentPrice;
                }

                //当前涨跌幅与最大最小值相比，取最大最小值
                if (percent > maxPercent) {
                    maxPercent = percent;
                }
                if (percent < minPercent) {
                    minPercent = percent;
                }
//
//                //如果均价大于max，则max等于均价；如果均价小于min，则min等于均价
//                if (averagePrice > max) {
//                    max = averagePrice;
//                }
//                if (averagePrice < min) {
//                    min = averagePrice;
//                }
//
                volmax = Math.max(minutesData.chengjiaoliang, volmax);
                minutesDatas.add(minutesData);
            }

            if (lastClose > max) {
                max = lastClose;
            }

            if (lastClose < min) {
                min = lastClose;
            }

            if (maxmin == 0) {
                maxmin = lastClose * 0.02f;
            }

            mMinutesChart.setYLabelColors(PriceColorUtil.getPriceColor(getContext(),min, lastClose), PriceColorUtil.getPriceColor(getContext(),max, lastClose));

            mMinutesChart.setBarMaxText(" ");  //柱状图只设置最大值

            mMinutesChart.setBarMaxValue(volmax);

            mMinutesChart.setMaxVolume("成交量：" + VolumeUtils.getVolUnit(volmax));

            mMinutesChart.setLineMaxMinValue(max, min, ((max - lastClose) / lastClose), ((min - lastClose) / lastClose));
//            mMinutesChart.setMaxMin(max, min, maxPercent / 100, minPercent / 100, 5);//必须放在前面
            mMinutesChart.setBaseLine(lastClose);//设置的是折线图基准线
            mMinutesChart.setData(getMinutesCount(), minutesDatas, 0, isZS);
            mMinutesChart.invalidate();

        }

        dispatchTimerHandler();

    }

    public String[] getMinutesCount() {
        return new String[1500];
    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    public void networkError() {

    }

    @Override
    public void onValueSelected(int xIndex, Entry klineEntry, Entry affilateEntry) {
        mMinutesChart.requestDisallowInterceptTouchEvent(true);
//        QuoteStockInfoActivity.canRefresh = false;
//        Log.e("touch", "onValueSelected");
//        if (isFullScreen) {
//            MinutesData kData = (MinutesData) klineEntry.getData();
//            float baseClose;
//            if (xIndex == 0) {
//                baseClose = kData.lastClose;
//            } else {
//                baseClose = kData.lastClose;
//            }
//            String color = kData.chengjiaojia > baseClose ? upColor : (kData.chengjiaojia == baseClose ? equalColor : downColor);
//
//            highTime.setText(kData.time);
//
//            highOpen.setText(Html.fromHtml(String.format("<font color='%s'>价格</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(kData.chengjiaojia))));
//            highHigh.setText(Html.fromHtml(String.format("<font color='%s'>涨跌</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(kData.percentage) + "%")));
//
//            highLow.setText("成交量 " + VolumeUtils.getVolUnit(kData.chengjiaoliang) + "");
//            color = kData.chengjiaojia > baseClose ? upColor : (kData.chengjiaojia == baseClose ? equalColor : downColor);
//            highClose.setText(Html.fromHtml(String.format("<font color='%s'>成交均价</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(kData.junjia))));
//            highFu.setVisibility(GONE);
//            if (chartTopHigh != null) {
//                chartTopHigh.removeAllViews();
//            }
//            chartTopHigh.addView(v);
//        }
    }

    @Override
    public void onValueNothing() {
        mMinutesChart.requestDisallowInterceptTouchEvent(false);
//        QuoteStockInfoActivity.canRefresh = true;
//        EventBus.getDefault().post(new BusUtils.refreshStatus(true));
//        if (isFullScreen) {
//            chartTopHigh.removeAllViews();
////            Log.e("touch", "onValueNothing");
//        }
    }


//
//    boolean firstClearChart = true;
//
//    @Subscribe
//    public void onEventMainThread(BusUtils.BusSnapData busData) {
//        try {
//            QuoteStockInfoSnapData data = busData.getData();
//            if (minuteList != null
//                    && !TextUtils.isEmpty(QuoteStockInfoActivity.stockCode)
//                    && data.getData().getCode().equals(QuoteStockInfoActivity.stockCode)) {
//                //快照数据转分时数据
//                QuoteStockMinutesData.DataBean dataBean = snapDataToMin(busData.getData());
//                long time = dataBean.getTime();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
//                final String dateStr = simpleDateFormat.format(time);
////                Log.e(TAG, "dateStr=" + dateStr);
//                AppBaseNetWork.getInstance().isStockOpeningTime(new AppBaseNetWork.StateCallback() {
//                    @Override
//                    public void isSuccess(boolean isSuccess) {
//                        if (isSuccess && firstClearChart && dateStr.equals("09:30") &&  mMinutesChart!= null  && minuteList != null ) {
//                            firstClearChart = false;
////                            Log.e(TAG, "清理 chart");
//                            mMinutesChart.clear();
//                            minuteList.clear();
//                        }
//                    }
//                });
//
//                handleLastMinData(dataBean);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//
//    /**
//     * 处理最后一分钟的数据
//     *
//     * @param data data
//     */
//    private void handleLastMinData(QuoteStockMinutesData.DataBean data) {
//        try {
//            //1.查看当前集合是否加载过数据
//            //2.已经加载过数据
//            //3.没加载过数据
//            if (minuteList != null &&
//                    minuteList.size() != 0) {
//                //判断时间
//                int dataSize = minuteList.size();
//                int lastIndex = dataSize - 1;
//                long oldTime = minuteList.get(lastIndex).getTime();
//                long newTime = data.getTime();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
//                String oldStr = simpleDateFormat.format(oldTime);
//                String newStr = simpleDateFormat.format(newTime);
////                Log.e(TAG, "oldStr=" + oldStr);
////                Log.e(TAG, "newStr=" + newStr);
////                DateTime oldDate = new DateTime(oldTime);
////                DateTime newDate = new DateTime(newTime);
//                Date oldDate = new Date(oldStr);
//                Date newDate = new Date(newStr);
//
//                if (newDate.after(oldDate)) {
//                    //添加数据
//                    minuteList.add(data);
////                    chartBaseInit(quoteStockMinutesDatas);
//                    addMinData(data);
////                    Log.e(TAG, "新数据");
////                    dataRefreshFinish();
//                } else if (oldStr.equals(newStr)) {
//                    //替换数据
////                    Log.e(TAG, "相同数据");
//                    minuteList.remove(lastIndex);
//                    minuteList.add(data);
////                    chartBaseInit(quoteStockMinutesDatas);
//                    replaceMinData(data);
////                    dataRefreshFinish();
//                }
////                lastPointBeating();
//            } else {
//                //加载数据
////                long time = data.getTime();
////                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
////                String dateStr = simpleDateFormat.format(time);
////                如果时间点为9：30 则使用快照数据
//                minuteList = new ArrayList<>();
////                List<QuoteStockMinutesData.DataBean> list = new ArrayList<>();
////                list.add(data);
//                minuteList.add(data);
//                refreshData();
////                } else {
////                    firstRequest();
////                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
//
//
//    /**
//     * 添加分时数据
//     *
//     * @param data data
//     */
//    private void addMinData(QuoteStockMinutesData.DataBean data) {
//        if (lineDataSet != null) {
//            int linDataCount = lineDataSet.getEntryCount();
//            if (linDataCount != 0) {
//                int lineDataIndex = linDataCount - 1;
//                lineDataSet.addEntry(new com.github.mikephil.charting.data.Entry((float) data.getCurrent(), lineDataIndex + 1));
//                lineDataSet.notifyDataSetChanged();
//            }
//        }
//
//        if (lineAverage != null) {
//            int lineAvgCount = lineAverage.getEntryCount();
//            if (lineAvgCount != 0) {
//                int lineAvgIndex = lineAvgCount - 1;
//                lineAverage.addEntry(new com.github.mikephil.charting.data.Entry((float) data.getAvg(), lineAvgIndex + 1));
//                lineAverage.notifyDataSetChanged();
//            }
//        }
//
//        if (barDataSet != null) {
//            int barEntryCount = barDataSet.getEntryCount();
//            if (barEntryCount != 0) {
//                int barIndex = barEntryCount - 1;
//                barDataSet.addEntry(new BarEntry((float) data.getVolume(), barIndex + 1));
//                barDataSet.notifyDataSetChanged();
//            }
//        }
//
//        if (lineChart != null) {
//            lineChart.notifyDataSetChanged();
//            lineChart.postInvalidate();
//        }
//
//        if (barChart != null) {
//            barChart.notifyDataSetChanged();
//            barChart.postInvalidate();
//        }
//    }
//
//    /**
//     * 替换最后一条数据
//     *
//     * @param data 分时数据
//     */
//    private void replaceMinData(QuoteStockMinutesData.DataBean data) {
//        if (lineDataSet != null) {
//            int linDataCount = lineDataSet.getEntryCount();
//            if (linDataCount != 0) {
//                int lineDataIndex = linDataCount - 1;
//                lineDataSet.removeEntry(lineDataIndex);
//                lineDataSet.addEntry(new com.github.mikephil.charting.data.Entry((float) data.getCurrent(), lineDataIndex));
//                lineDataSet.notifyDataSetChanged();
//            }
//        }
//
//        if (lineAverage != null) {
//            int lineAvgCount = lineAverage.getEntryCount();
//            if (lineAvgCount != 0) {
//                int lineAvgIndex = lineAvgCount - 1;
//                lineAverage.removeEntry(lineAvgIndex);
//                lineAverage.addEntry(new com.github.mikephil.charting.data.Entry((float) data.getAvg(), lineAvgIndex));
//                lineAverage.notifyDataSetChanged();
//            }
//        }
//
//        if (barDataSet != null) {
//            int barEntryCount = barDataSet.getEntryCount();
//            if (barEntryCount != 0) {
//                int barIndex = barEntryCount - 1;
//                barDataSet.removeEntry(barIndex);
//                barDataSet.addEntry(new BarEntry((float) data.getVolume(), barIndex));
//                barDataSet.notifyDataSetChanged();
//            }
//        }
//
//        if (lineChart != null) {
//            lineChart.notifyDataSetChanged();
//            lineChart.postInvalidate();
//        }
//
//        if (barChart != null) {
//            barChart.notifyDataSetChanged();
//            barChart.postInvalidate();
//        }
//    }
//
//    /**
//     * 快找数据转为分时数据
//     *
//     * @param data data
//     * @return data
//     */
//    private QuoteStockMinutesData.DataBean snapDataToMin(QuoteStockInfoSnapData data) {
//        QuoteStockMinutesData.DataBean minData = new QuoteStockMinutesData.DataBean();
//        try {
//            QuoteStockInfoSnapData.DataBean snapData = data.getData();
//            Log.e(TAG, "snapData=" + snapData);
//            float price = Float.parseFloat(snapData.getPrice() + "");
//            float prev = Float.parseFloat(snapData.getPrev() + "");
//            float volume = Float.parseFloat(snapData.getVolume() + "");
//            float avg = Float.parseFloat(snapData.getSp1() + "");
//            String dealTime = snapData.getDealtime();
//
//            dealTime = dealTime.replace("-0400", "+0800");
//            Date date = new Date(dealTime);
//
//            float change = BigDecimalUtils.sub(price, prev, 2);
//            float div = BigDecimalUtils.div(change, prev, 4);
//            float percent = BigDecimalUtils.mul(div, 100, 2);
//            float tempVolume = 0;
//            float lastMinVolume = volume;
//            List<QuoteStockMinutesData.DataBean> currentList = minuteList;
//            if (minuteList != null && currentList != null && currentList.size() > 0) {
//
//                long newTime = date.getTime();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
//                String newStr = simpleDateFormat.format(newTime);
//                Date newDate = new Date(newStr);
//                for (int i = 0; i < currentList.size(); i++) {
//                    QuoteStockMinutesData.DataBean temp = currentList.get(i);
//                    long oldTime = temp.getTime();
//                    String oldStr = simpleDateFormat.format(oldTime);
//                    Date oldDate = new Date(oldStr);
//                    if (newDate.after(oldDate)) {
//                        tempVolume += temp.getVolume();
//                    }
//                }
//                lastMinVolume = BigDecimalUtils.sub(volume, tempVolume, 2);
//                QuoteStockMinutesData.DataBean temp = currentList.get(currentList.size() - 1);
//                avg = Float.parseFloat(temp.getAvg() + "");
//            }
//
//            minData.setCurrent(price);
//            minData.setPercent(percent);
//            minData.setLast_close(prev);
////            Log.e(TAG, "snapVolume=" + volume);
////            Log.e(TAG, "tempVolume=" + tempVolume);
////            Log.e(TAG, "lastMinVolume=" + lastMinVolume);
//            minData.setVolume(lastMinVolume);
//            minData.setAvg(avg);//均价暂无法计算
//            minData.setTime(date.getTime());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return minData;
//    }
//

}
